import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { Button, Checkbox, Col, DatePicker, Form, InputNumber, Modal, Row, Space, Spin, Tabs, Tooltip, TreeSelect, message } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { SHTG_CHECKSTATE, SHZ_CHECKSTATE } from '../../../Acommon';
import {
  downloadTemplate,
  getFileNameNotType,
  getInvoiceCode,
  getLevelZeroJson,
  getLoadMapList,
  getPersonalInfo,
  getPosIDs,
  getPosName,
  getSelectDataMapList,
  getTenantID,
  getUserDepID,
  getUserDepName,
  getUserID,
  getUserName,
  splitFileUrl,
} from '@/utils';
import { DownloadOutlined, CheckOutlined, SaveOutlined, UploadOutlined, SearchOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { connect, history } from 'umi';
import {
  DetailedServices,
  addDiffServices,
  detailDiffServices,
  editDiffServices,
  manualUpServices,
  editDetailServices,
  approvedInventorySerivice,
} from '../services/UpdataService';
import { UpdataPlanModal } from './UpdataPlanModal';
import { PDCYflowBusinessType, orderType, requestController } from '../common/Format';
import '../common/style.less';
import moment from 'moment';
import DifferTable from './DifferTable';
import MyIcon from '@/components/MyIcon';
import { UploadFormCommonTwo } from '@/components/UploadFormTwo';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '@/pages/PurchaseManage/Acomponents/RevokeModal';
import { syncPDFtoOAServices } from '../services/DetailOAService';

function addDisabledToTreeData(originalTreeData) {
  const newTreeData = originalTreeData?.map((node) => {
    const newNode = { ...node, disabled: true }; // 复制节点并添加disabled属性

    if (node.children) {
      newNode.children = addDisabledToTreeData(node.children); // 递归处理子节点
    }

    return newNode;
  });

  return newTreeData;
}

const UpdataView = ({ curRes, locationProps }) => {
  /** ================================== 初始化变量 start ================================ */
  const styleFixCls = 'contract-styfixcls-';

  const { pageType, record } = locationProps?.state;
  const isDetail = pageType === 'detail';

  const [acceptForm] = Form.useForm();
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);
  const [ProjectModal, setProjectModal] = useState<Record<string, any>>({}); //是否显示选择盘点计划弹窗

  const [selectPlan, setSelectPlan] = useState<any>({}); //选择的盘点计划
  const [detailInfo, setDetailInfo] = useState<any>({}); //详情信息
  const [diffList, setDiffList] = useState<any>([]); //盘点前后列表
  const [saveFlag, setSaveFlag] = useState<string>(''); //是否提交

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  // 工作流
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  /** ========================================== 差异明细 service start ================================================= */

  /** 详情 service */
  const { detailDiffRun, detailDiffLoading, reloadRequest } = detailDiffServices((res) => {
    if (res && res.msgFlag) {
      setDetailInfo({
        ...res?.obj,
        // createTime: moment(res?.obj?.createTime).format('YYYY-MM-DD'),
      });
      if (saveFlag === '2') {
        /** 发起审批 */
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      }
      message.success(res?.msg);
    }
  });

  const { DetailPushRun, Detaildata, getDetailReload, taskPushPagination, taskPushLoading } = DetailedServices(curRes);

  /** 添加 service */
  const { addDiffRun, addDiffLoading } = addDiffServices((res) => {
    if (res.msgFlag) {
      message.success('添加成功');
      detailDiffRun({ id: res?.obj?.id, inventoryID: res?.obj?.inventoryID });
    }
  });

  /** 编辑 service */
  const { editDiffRun, editDiffLoading } = editDiffServices((res) => {
    if (res.msgFlag) {
      detailDiffRun({ id: detailInfo?.id, inventoryID: detailInfo?.inventoryID });
    }
  });

  /** 修改资产回调 */
  const editDetailCallback = (res: any) => {
    if (selectPlan?.info?.inventoryID || record?.inventoryID) {
      const obj: any = {
        inventoryID: selectPlan?.info?.inventoryID || record?.inventoryID,
        page: 1,
        rows: 10,
        changeState: '0,2,3',
        // isInventory: 0,
      };
      DetailPushRun(obj);
    }
  };

  /** 修改资产接口 */
  const { editDetailRun, editDetailLoading } = editDetailServices(editDetailCallback);

  /** ========================================== 差异明细 service end ================================================= */

  /** 保存盘点前后列表事件 */
  const onSaveDiffFun = (list) => {
    setDiffList(list);
  };

  /**
   * 上传按钮loading
   */
  const [uploadLoading, setUploadLoading] = useState<boolean>(false);

  /** 表单配置项 */
  const fromConfig: any = useMemo(() => {
    return [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: isDetail,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createrName`,
            label: `盘点人`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `inventoryTitle`,
            label: `事项名称/盘点计划`,
            component: 'Input',
            disabled: true,
            required: !isDetail,
            colSpan: 1,
            placeholder: '请选择',
            contentAfter: !isDetail ? (
              <a>
                <SearchOutlined onClick={() => setProjectModal({ isShow: true })} />
              </a>
            ) : null,
          },
          {
            field: `rangeAssetClassID`,
            label: `资产类型范围`,
            component: 'Render',
            colSpan: 1,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder="自动带出"
                  multiple
                  style={{
                    width: '100%',
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  treeData={addDisabledToTreeData(assetType)}
                  treeCheckable={true}
                  maxTagCount={3}
                  disabled
                />
              );
            },
          },
          {
            field: `rangeDeptID`,
            label: `部门范围`,
            component: 'Render',
            colSpan: 2,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder="自动带出"
                  multiple
                  style={{
                    width: '100%',
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'text',
                    value: 'id',
                    children: 'children',
                  }}
                  treeData={getLevelZeroJson()}
                  treeCheckable={true}
                  maxTagCount={6}
                  showCheckedStrategy={TreeSelect.SHOW_PARENT}
                  treeDefaultExpandAll={true}
                  disabled
                />
              );
            },
          },

          {
            field: `rangeStartDate`,
            label: `取得开始时间`,
            component: 'Input',
            colSpan: 1,
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `rangeEndDate`,
            label: `取得结束时间`,
            component: 'Input',
            colSpan: 1,
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `billNum`,
            label: `账面总数`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,

            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },
          {
            field: `billSum`,
            label: `账面总额`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },
          {
            field: `inventoryNum`,
            label: `盘点总数`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },
          {
            field: `inventorySum`,
            label: `盘点总额`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },

          {
            field: `lossSum`,
            label: `盘亏汇总`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },
          {
            field: `surplusSum`,
            label: `盘盈汇总`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            render: (text, record) => {
              return <InputNumber disabled={isDetail} placeholder={'请输入'} min={0} precision={2} />;
            },
          },
          {
            field: `inventoryInfo`,
            label: `盘点说明`,
            component: 'InputTextArea',
            disabled: isDetail,
            placeholder: '请输入',
            required: !isDetail,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `inventoryURL`,
            label: `上传结果`,
            component: 'Render',
            disabled: !selectPlan?.info?.inventoryID,
            ishidden: isDetail,
            placeholder: '请选择',
            render: (text, record) => {
              return (
                <>
                  <UploadFormCommonTwo
                    form={acceptForm}
                    fileFormName={'inventoryURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={false}
                    accept={'.db'}
                    url={`/assetInventory/uploadFile?inventoryID=${selectPlan?.info?.inventoryID || record?.inventoryID}`}
                    downloadUrl={''} // 下载
                    disabledUpload={!selectPlan?.info?.inventoryID}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(res: any, info: any) => {
                      // if (res && res.msgFlag) {
                      //   acceptForm?.setFieldsValue({
                      //     inventoryURL: '已上传',
                      //   });
                      // }
                      if (info?.file?.status === 'done' && info?.file?.response?.obj?.lossSum) {
                        acceptForm?.setFieldsValue({
                          lossSum: info?.file?.response?.obj?.lossSum,
                        });
                      }
                      if (selectPlan?.info?.inventoryID || record?.inventoryID) {
                        const obj: any = {
                          inventoryID: selectPlan?.info?.inventoryID || record?.inventoryID,
                          page: 1,
                          rows: 10,
                          changeState: '0,2,3',
                          // isInventory: 0,
                        };
                        DetailPushRun(obj);
                      }
                    }}
                    defaultFiles={''}
                    // maxFile={1}
                    hintTitle={'且只能上传 1 个！'}
                    fieldBusiPath={'reportURL'}
                    delFunc={(delFilePath) => {
                      // acceptForm?.setFieldsValue({
                      //   assetImage: '',
                      // });
                    }}
                    uploadLoading={uploadLoading}
                    setUploadLoading={setUploadLoading}
                  >
                    扫码枪导出文件
                  </UploadFormCommonTwo>
                </>
              );
            },
          },
          {
            field: `importPicture`,
            label: `上传图片集`,
            component: 'Render',
            disabled: !selectPlan?.info?.inventoryID,
            ishidden: isDetail,
            placeholder: '请选择',
            render: (text, record) => {
              return (
                <>
                  <UploadFormCommonTwo
                    form={acceptForm}
                    fileFormName={'importPicture'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={false}
                    accept={'.zip'}
                    disabledUpload={!selectPlan?.info?.inventoryID}
                    id={selectPlan?.info?.inventoryID}
                    url={`/assetInventoryDifference/importPicture?inventoryID=${selectPlan?.info?.inventoryID || record?.inventoryID}`}
                    downloadUrl={'/assetInfo/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(res: any, info: any) => {
                      // if (res && res.msgFlag) {
                      //   acceptForm?.setFieldsValue({
                      //     importPicture: '已上传',
                      //   });
                      // }
                      if (selectPlan?.info?.inventoryID || record?.inventoryID) {
                        const obj: any = {
                          inventoryID: selectPlan?.info?.inventoryID || record?.inventoryID,
                          page: 1,
                          rows: 10,
                          changeState: '0,2,3',
                          // isInventory: 0,
                        };
                        DetailPushRun(obj);
                      }
                    }}
                    defaultFiles={''}
                    // maxFile={1}
                    hintTitle={'且只能上传 1 个！'}
                    fieldBusiPath={'reportURL'}
                    delFunc={(delFilePath) => {
                      // acceptForm?.setFieldsValue({
                      //   assetImage: '',
                      // });
                    }}
                    uploadLoading={uploadLoading}
                    setUploadLoading={setUploadLoading}
                  >
                    扫码枪导出图片
                  </UploadFormCommonTwo>
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: (
          <>
            <DifferTable
              inventoryID={selectPlan?.info?.inventoryID || record?.inventoryID}
              onSaveDiffFun={onSaveDiffFun}
              isDetail={isDetail}
              detailInfo={detailInfo}
              Detaildata={Detaildata}
              taskPushPagination={taskPushPagination}
              taskPushLoading={taskPushLoading || uploadLoading}
              editDetailRun={editDetailRun}
              editDetailLoading={editDetailLoading}
            />
          </>
        ),
      },
    ];
  }, [assetType, isDetail, selectPlan, record]);

  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: acceptForm,
    schemas: fromConfig,
  });

  /** 添加编辑 */
  const onSaveFun = (isSubmit: string) => {
    methods?.validateFields().then((values) => {
      delete values.importPicture;
      delete values.inventoryURL;
      const tempObj = {
        ...values,
        createTime: moment(values?.createTime).format('YYYY-MM-DD HH:mm:ss'),
        rangeAssetClassID: values?.rangeAssetClassID?.join(','),
        rangeDeptID: values?.rangeDeptID?.join(','),
        rangeEndDate: values?.rangeEndDate ? moment(values?.rangeEndDate).format('YYYY-MM-DD HH:mm:ss') : '',
        rangeStartDate: values?.rangeStartDate ? moment(values?.rangeStartDate).format('YYYY-MM-DD HH:mm:ss') : '',
        inventoryState: selectPlan?.row?.inventoryState,
        inventoryID: selectPlan?.info?.inventoryID,
        differenceSet: diffList,
      };

      setSaveFlag(isSubmit);

      /** 只有第一回是添加，其他都是暂存 */
      if ((locationProps?.state?.pageType == 'add' && isSubmit == '1' && !detailInfo?.id) || (isSubmit == '2' && !detailInfo?.id)) {
        // 添加
        addDiffRun(tempObj);
      } else {
        // 编辑
        editDiffRun({ ...detailInfo, ...tempObj, id: detailInfo?.id, inventoryID: detailInfo?.inventoryID });
      }
    });
  };

  /** 审核通过后要调的接口 */
  const { approvedInventoryRun, approvedInventoryLoading } = approvedInventorySerivice((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
    }
  });

  /** 审核中，审核通过/作废 开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {});
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (detailInfo?.state && detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1001` && detailInfo?.checkState == SHZ_CHECKSTATE()) {
      setIsSHTGFlag(true);
    }
    if (isSHTGFlag && detailInfo?.checkState == SHTG_CHECKSTATE()) {
      approvedInventoryRun({ ...detailInfo, workflowResult: true });
      syncPDFtoOARunfun(detailInfo);
    }
  }, [detailInfo?.state, detailInfo?.checkState]);

  useEffect(() => {
    if (selectPlan?.info?.inventoryID || record?.inventoryID || detailInfo?.inventoryID) {
      const obj: any = {
        inventoryID: selectPlan?.info?.inventoryID || record?.inventoryID || detailInfo?.inventoryID,
        page: 1,
        rows: 10,
        changeState: '0,2,3',
        useCompanyID: detailInfo?.createCompanyID || detailInfo?.createDepartmentID,
        // isInventory: 0,
      };
      DetailPushRun(obj);
    }
  }, [selectPlan?.info?.inventoryID || record?.inventoryID || detailInfo?.inventoryID]);

  /** 选中的盘点计划数据回显 */
  useEffect(() => {
    if (selectPlan?.row?.id) {
      methods?.setFieldsValue({
        inventoryTitle: selectPlan?.row?.inventoryTitle,
        rangeAssetClassID: selectPlan?.row?.rangeAssetClassID?.split(','),
        rangeDeptID: selectPlan?.row?.rangeDeptID?.split(','),
        rangeStartDate: selectPlan?.row?.rangeStartDate ? selectPlan?.row?.rangeStartDate : '',
        rangeEndDate: selectPlan?.row?.rangeEndDate ? selectPlan?.row?.rangeEndDate : '',
        billNum: selectPlan?.info?.billNum,
        billSum: selectPlan?.info?.billSum,
        inventoryNum: selectPlan?.info?.inventoryNum,
        inventorySum: selectPlan?.info?.inventorySum,
        lossSum: selectPlan?.info?.lossSum,
        surplusSum: selectPlan?.info?.surplusSum,
      });
    }
  }, [selectPlan]);

  useEffect(() => {
    if (detailInfo?.id) {
      methods?.setFieldsValue({
        ...detailInfo,
        rangeAssetClassID: detailInfo?.rangeAssetClassID?.split(','),
        rangeDeptID: detailInfo?.rangeDeptID?.split(','),
        rangeStartDate: detailInfo?.rangeStartDate ? moment(detailInfo?.rangeStartDate).format('YYYY-MM-DD') : '',
        rangeEndDate: detailInfo?.rangeEndDate ? moment(detailInfo?.rangeEndDate).format('YYYY-MM-DD') : '',
        createTime: moment(detailInfo?.createTime),
      });
    }
  }, [detailInfo]);

  /** 初始化 */
  useEffect(() => {
    if (pageType === 'add') {
      methods?.setFieldsValue({
        createTime: moment(new Date()),
        applyCode: getInvoiceCode('PDCY'),
        createrName: getUserName(),
        createPhone: getPersonalInfo()?.phoneMobile || '',
        createDepartmentName: getUserDepName(),
        createPositionName: getPosName(),
      });
    } else {
      detailDiffRun({ id: record?.id, inventoryID: record?.inventoryID });
    }
  }, []);

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll?.ASSET_SUMMARY_STATUS}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`;
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [detailInfo]);

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 申请页ref */
  const { confirm } = Modal;

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = useMemo(() => {
    let items: any[] = [
      {
        label: '申请详情',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>
            <div
              className="tabsBodyBottomBtn"
              style={{
                textAlign: 'center',
              }}
            >
              <Space className="space-button-all">
                {((!detailInfo?.state ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1000` && !detailInfo?.checkState) ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1003` &&
                    detailInfo?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1003`)) &&
                  detailInfo?.createrID == getUserID()) ||
                locationProps?.state?.pageType === 'add' ? (
                  <Button type={'primary'} onClick={() => onSaveFun('2')}>
                    提交
                  </Button>
                ) : null}
                <Button danger onClick={closeCurrent}>
                  关闭
                </Button>
              </Space>
              {/* 工作流审批按钮 */}
              {/* <WorkflowHndTaskBtn
                flowDetailInfo={detailInfo}
                requestController={requestController()}
                reloadCallback={reloadRequest}
                flowBusinessType={PDCYflowBusinessType()}
              /> */}
            </div>
          </div>
        ),
      },
    ];
    return items;
  }, [assetType, selectPlan]);

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        position="top"
        detailInfo={detailInfo}
        locationProps={locationProps}
        onSaveFun={onSaveFun}
        reloadRequest={reloadRequest}
        PDCYflowBusinessType={PDCYflowBusinessType}
        requestController={requestController}
        changeRevoke={changeRevoke}
      />
    );
  };

  return (
    <div className={'apply-update-UpdataIntentBox'}>
      <Spin spinning={detailDiffLoading || addDiffLoading || editDiffLoading}>
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`}>
            <Tabs className={pageStyles['commonTabs']} type="card" items={tabsItem} destroyInactiveTabPane={true} tabBarExtraContent={contactsTabsExtra()} />
          </Col>
        </Row>

        {ProjectModal?.isShow && (
          <UpdataPlanModal
            onSave={(value) => {
              setSelectPlan(value);
            }}
            onClose={() => {
              setProjectModal({});
            }}
            curRes={curRes}
            selectPlan={selectPlan}
          />
        )}

        {/* 工作流-----审批记录 */}
        {detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`] && (
          <WorkflowChedkRecord
            curRes={curRes}
            dataDetailInfo={detailInfo}
            flowBusinessType={PDCYflowBusinessType()}
            requestController={requestController()}
            reloadPageCallback={() => {
              detailDiffRun({ id: detailInfo?.id, inventoryID: detailInfo?.inventoryID });
            }} // 刷新方法-详情方法
            revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.ASSET_SUMMARY_STATUS}1000`}
            allBtnFuncQuqry={workflowPowerAllBtn}
            tabPaneHeight={0.35}
            isCheckDrawer={true}
            isShowCollapse={isShowWorkRecord}
            changeCollapse={(val) => {
              setIsShowWorkRecord(val);
            }}
            cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.ASSET_SUMMARY_STATUS}1003`}
            isSyncArchive={true}
          />
        )}

        {/* 撤销弹窗 */}
        {invalidState?.isShow && (
          <RevokeModal
            resObj={invalidState?.resObj}
            revokeRequestUrl={'/assetInventoryDifference/revoke'}
            onClose={() => setInvalidState({})}
            reqBody={{
              id: invalidState?.resObj?.id,
              state: `${getTenantID()}${ILoadMapTypeAll?.ASSET_SUMMARY_STATUS}1000`,
            }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.inventoryTitle}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={() => {
              history.push({
                pathname: locationProps?.state?.returnPathName,
                state: {
                  delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                  returnPathName: locationProps?.state?.returnPathName,
                },
              });
            }}
          />
        )}

        {/* 工作流-----发起流程审批弹窗 */}
        {workFlowInfoObj?.showWorkFlowModal && (
          <WorkflowSwitchModal
            openVisible={workFlowInfoObj?.showWorkFlowModal}
            businessInfoObj={workFlowInfoObj?.selectFlowRows}
            requestController={requestController()}
            orderType={orderType()}
            category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`}
            businessCategory={``}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            reloadInfoCallback={async () => {
              history.push({
                pathname: '/inventorySummaryController/manage',
                state: {
                  delRouterNameSource: history.location.pathname,
                },
              });
            }}
            openFlowChangeModal={setShowSwitchFlow}
            onClose={() => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                showWorkFlowModal: false,
              });
            }}
            replaceStrObj={{ own: 'own', workflowType: 'category' }}
          />
        )}

        {/* 挑选流程组件 */}
        {showSwitchFlow && (
          <WorkflowNoDefaultTable
            openVisibleSwitch={showSwitchFlow}
            onCloseSwitch={closeSwitchFlowModal}
            requestController={requestController()}
            orderType={orderType()}
            category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`}
            businessCategory={``}
            saveSelectFlowID={(flowId: string) => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                saveNoDefaultFlowID: flowId,
              });
            }}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          />
        )}
      </Spin>
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdataView);
